#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright @ 2014 OPS, Qunar Inc. (qunar.com)
#
# Author: tingfang.bao <tingfang.bao@qunar.com>
# DateTime: 15-3-10 下午4:44
import json
from database import db_session, engine
from flask import Flask
from models2 import users

app = Flask(__name__)


@app.teardown_appcontext
def shutdown_session(exception=None):
    db_session.remove()


@app.route("/")
def index():
    r = users.select().execute()
    ret = []
    for user in r:
        ret.append({
            "name": user.username,
            "id": user.id,
            "email": user.email
        })
    return json.dumps(ret)


@app.route("/row")
def row():
    user = users.select(users.c.id == 1).execute().first()
    return json.dumps({
        "id": user['id'],
        "name": user['username'],
        "email": user['email']
    })


@app.route('/add')
def create():
    con = engine.connect()
    con.execute(users.insert(), username="baotingfang", email="tingfang.bao@qunar.com")
    con.close()
    return 'added'


@app.route('/sql')
def sql():
    user = engine.execute('select * from users where id =:1', [1]).first()
    return json.dumps({
        "id": user['id'],
        "name": user['username'],
        "email": user['email']
    })


if __name__ == '__main__':
    app.run(debug=True)